﻿using System;
using System.Collections.Generic;
using Legazpi.Payroll.BusinessLogic.Services.Interfaces;
using Legazpi.Payroll.DataAccess.Repositories;
using System.Data.Entity;
using Legazpi.Payroll.DataAccess.DataObjects;
using Legazpi.Payroll.DataAccess.Base;
using System.Linq;

namespace Legazpi.Payroll.BusinessLogic.Services
{
    public class DetachmentService : IDetachmentService
    {
        #region Fields

        private DbContext _dbContext;
        private IDetachmentRepository _detachmentRepository;        
        private IDatabaseFactory _dbFactory;
        #endregion

        #region ctor

        public DetachmentService()
            : this(new DatabaseFactory())
        {

        }

        public DetachmentService(IDatabaseFactory dbFactory)
        {
            if (dbFactory == null) throw new ArgumentNullException("dbFactory");
            _dbFactory = dbFactory;
            DbContext = dbFactory.Get();
        }

        private DbContext DbContext
        {
            get { return _dbContext; }
            set
            {
                _dbContext = value;
                _detachmentRepository = new DetachmentRepository(_dbContext);                
            }
        }

        #endregion

        public Detachment GetById(int id)
        {
            return _detachmentRepository.GetById(id);
        }

        public IEnumerable<Detachment> GetAll()
        {
            return _detachmentRepository.GetAll();
        }

        public void Add(Detachment detachment)
        {
            _detachmentRepository.Add(detachment);
        }

        public void Update(Detachment detachment)
        {
            _detachmentRepository.Update(detachment);
        }

        public void Delete(int id)
        {
            var Detachment = GetById(id);
            if (Detachment != null)
                _detachmentRepository.Delete(Detachment);
        }

        public bool Save()
        {
            string message;
            _detachmentRepository.Save(out message);
            return message == "Saved";
        }


        public IEnumerable<Detachment> GetAllByClientId(int clientId)
        {
            return _detachmentRepository.GetQuery()
                .Where(x => x.Sector.ClientId == clientId).ToList();
        }

        public Detachment GetByQuery(int sectorId, int positionId)
        {
            return _detachmentRepository.Get(x => x.SectorId == sectorId && x.PositionId == positionId);
        }

    }
}
